import 'package:flutter/material.dart';
import 'package:flutter_architecture_samples_vanilla/models.dart';
import 'package:flutter_architecture_samples_vanilla/widgets/todo_item.dart';
import 'package:flutter_architecture_samples_vanilla/widgets/typedefs.dart';
import 'package:todos_app_core/todos_app_core.dart';

import '../screen/detail_screen.dart';

class TodoList extends StatelessWidget {
  final bool loading;
  final List<Todo> filteredTodos;
  final TodoRemover removeTodo;
  final TodoAdder addTodo;
  final TodoUpdater updateTodo;
  const TodoList(
      {required this.loading,
      Key? key,
      required this.addTodo,
      required this.filteredTodos,
      required this.updateTodo,
      required this.removeTodo})
      : super(key: ArchSampleKeys.todoList);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: loading
          ? Center(
              child: CircularProgressIndicator(
              key: ArchSampleKeys.todosLoading,
            ))
          : ListView.builder(
              itemBuilder: (context, index) {
                final todo = filteredTodos[index];
                return TodoItem(
                  todo: todo,
                  onDismissed: (direction) {
                    _removeTodo(context, todo);
                  },
                  onCheckboxChanged: (isDone) {
                    updateTodo(
                      todo,
                      complete: !todo.complete,
                    );
                  },
                  onTap: () {
                    Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                      return DetailScreen(
                          key: ArchSampleKeys.todoDetailsScreen,
                          onDelete: () {
                            _removeTodo(context, todo);
                          },
                          todo: todo,
                          addTodo: addTodo,
                          updateTodo: updateTodo);
                    }));
                  },
                );
              },
              itemCount: filteredTodos.length),
    );
  }

  void _removeTodo(BuildContext context, Todo todo) {
    removeTodo(todo);
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      key: ArchSampleKeys.snackbar,
      duration: Duration(seconds: 2),
      content: Text(
        ArchSampleLocalizations.of(context)!.todoDeleted(todo.task),
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
      action: SnackBarAction(
        label: ArchSampleLocalizations.of(context)!.undo,
        onPressed: () {
          addTodo(todo);
        },
      ),
    ));
  }
}
